<template>
  <div class="problemtrain" id="problemtrain">
    <a-tabs default-active-key="1">
      <a-tab-pane key="1" tab="知识库管理">
        <div class="main-content">
          <div class="main-inner-left">
            <div>
              <a-button @click="CategoryOpenModel('CategoryEDI')">编辑</a-button>
              <a-button @click="CategoryOpenModel('CategoryDEL')">删除</a-button>
              <a-button @click="CategoryOpenModel('CategoryCRE')">新增</a-button>
              <!-- <a-upload
                name="multipartFile"
                :multiple="true"
                action="http://192.168.1.222:80/nlpcs/knowledgeBase/importExcel"
                :headers="headers"
                @change="handleChange"
              >
                <a-button>
                  <a-icon type="upload" />上传
                </a-button>
              </a-upload>-->
              <a :href="downUrl">下载</a>
              <!-- <a-button type="primary" icon="download" @click="handleExportXls('知识库管理')">导出</a-button> -->
              <a-upload
                name="file"
                :showUploadList="false"
                :multiple="false"
                :headers="tokenHeader"
                :action="importExcelUrl"
                @change="handleImportExcel"
              >
                <a-button type="primary" icon="import">导入</a-button>
              </a-upload>
            </div>
            <a-tree
              :load-data="onLoadData"
              :tree-data="treeData"
              :replaceFields="replaceFields"
              @select="onSelect"
            />
          </div>
          <div class="main-inner-right">
            <a-button @click="CategoryOpenModel('ScienceCRE')">新增</a-button>
            <a-table class="a_table" :data-source="SourceData" :columns="columns">
              <div slot="action2" slot-scope="text, record">
                <a-button @click="CategoryOpenModel('ScienceDEL',record)">删除</a-button>
                <a-button @click="CategoryOpenModel('ScienceEDI',record)">编辑</a-button>
                <a-button @click="CategoryOpenModel('ScienceINFO',record)">详情</a-button>
              </div>
            </a-table>
          </div>
        </div>
      </a-tab-pane>
      <a-tab-pane key="2" tab="核心词管理">
        <a-button @click="CategoryOpenModel('CoreWordCRE')">新增</a-button>
        <a-table class="a_table" :data-source="CoreWordsData" :columns="CoreWordscolumns">
          <div slot="action3" slot-scope="text, record">
            <a-button @click="CategoryOpenModel('CoreWordEDI',record)">编辑</a-button>
            <a-button @click="CategoryOpenModel('CoreWordDEL',record)">删除</a-button>
          </div>
        </a-table>
      </a-tab-pane>
    </a-tabs>

    <a-modal v-model="visible" title="类别" @ok="modelDetermine" @cancel="modelCancel">
      <div v-if="ModelType === 'CategoryEDI'">
        <h3>编辑</h3>
        <a-input v-model="CategoryName"></a-input>
      </div>
      <div v-else-if="ModelType === 'CategoryDEL'">
        <h3>删除</h3>
      </div>
      <div v-else-if="ModelType === 'CategoryCRE'">
        <h3>新增</h3>
        <a-input v-model="CategoryName"></a-input>
      </div>
      <div v-else-if="ModelType === 'ScienceCRE'">
        <span>核心词</span>
        <a-select style="width: 200px" @change="handleChange">
          <a-select-option
            v-for="(value,index) in CoreWordsData"
            default-value="value.coreWordsId_dictText"
            :key="index"
          >{{ value.content }}</a-select-option>
        </a-select>
        <span>标题</span>
        <a-input v-model="ScienceCRE.title"></a-input>
      </div>
      <div v-else-if="ModelType === 'ScienceEDI'">
        <h3>ScienceCRE编辑</h3>
        <span>核心词</span>
        <a-select style="width: 200px" @change="handleChange">
          <a-select-option
            v-for="(value,index) in CoreWordsData"
            :default-value="value.id"
            :key="index"
          >{{ value.content }}</a-select-option>
        </a-select>
        <span>标题</span>
        <a-input v-model="ScienceEDI.title"></a-input>
      </div>
      <div v-else-if="ModelType === 'ScienceINFO'">
        <h3>ScienceCRE详情</h3>
      </div>
      <div v-else-if="ModelType === 'CoreWordCRE'">
        <h3>核心词添加</h3>
        <a-input v-model="CoreWordName"></a-input>
      </div>
      <div v-else-if="ModelType === 'CoreWordEDI'">
        <h3>核心词编辑</h3>
        <a-input v-model="CoreWordName"></a-input>
      </div>
      <div v-else-if="ModelType === 'CoreWordDEL'">
        <h3>核心词删除</h3>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { getAction, postAction, putAction, deleteAction, downFile } from '@/api/manage'
import Vue from 'vue'
import { ACCESS_TOKEN } from "@/store/mutation-types"
export default {
  components: {},

  data() {
    return {
      queryParam: {},
      selectedRowKeys: [],
      tokenHeader: {'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)},

      downUrl: 'http://192.168.1.222:80/nlpcs/knowledgeBase/exportXls',
      importExcelUrl: 'http://192.168.1.222:80/nlpcs/knowledgeBase/importExcel',
      visible: false, //类目操作面板开关
      ModelType: '', //类目操作面板类型开关
      treeData: [], //类目树数据
      CategoryId: null, //标记类目id
      CategoryParentId: null, //标记类目父id
      CategoryName: '', //标记类目操作标题
      CoreWordName: '', //核心词名称用于添加、编辑
      CoreWordID: null, //核心词id用于编辑、删除
      //tree默认字段设置
      replaceFields: {
        title: 'name',
        key: 'id'
      },

      //知识库table数据
      SourceData: [],
      //知识库table模板
      columns: [
        { title: '问题', dataIndex: 'title', key: '1', width: 200 },
        { title: '关键词', dataIndex: 'coreWordsId_dictText', key: '2', width: 300 },
        {
          title: '操作',
          key: '3',
          ellipsis: true,
          scopedSlots: { customRender: 'action2' }
        }
      ],

      // 核心词table数据
      CoreWordsData: [],
      // 核心词table模板
      CoreWordscolumns: [
        { title: '核心词', dataIndex: 'content', key: '1', width: 700 },
        {
          title: '操作',
          key: '3',
          ellipsis: true,
          scopedSlots: { customRender: 'action3' }
        }
      ],

      // 添加知识data
      ScienceCRE: {
        title: '',
        coreWordsId: '',
        categoryPathId: null
      },
      // 编辑知识data
      ScienceEDI: {
        title: '',
        coreWordsId: '',
        categoryPathId: null,
        id: null
      },

      handleExportXls(fileName) {
        if (!fileName || typeof fileName != 'string') {
          fileName = '导出文件'
        }
        let param = { ...this.queryParam }
        if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
          param['selections'] = this.selectedRowKeys.join(',')
        }
        console.log("导出参数",param)
        downFile(this.downUrl, {}).then(data => {
          console.log(data)

          if (!data) {
            this.$message.warning('文件下载失败')
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
          } else {
            let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName + '.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) //下载完成移除元素
            window.URL.revokeObjectURL(url) //释放掉blob对象
          }
        })
      }
    }
  },
  created() {
    // 获取父目录
    this.getTreeCategory()
    this.getCoreWords()
  },
  mounted() {},
  methods: {
    // 获取父目录
    getTreeCategory() {
      getAction('/nlpcs/categoryPath/rootList', {})
        .then(res => {
          if (res.code != 200) {
            this.$message.info('获取目录失败')
          }
          this.treeData = res.result.records
        })
        .catch(err => {
          console.log(err)
        })
    },

    // 获取核心词列表
    getCoreWords() {
      getAction('/nlpcs/coreWords/list', {})
        .then(res => {
          this.CoreWordsData = res.result.records
        })
        .catch(err => {
          console.log(err)
        })
    },

    // 获取子目录 tree的监听事件
    onLoadData(treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children === 1) {
          resolve()
          return
        }
        setTimeout(() => {
          getAction('/nlpcs/categoryPath/rootList', {
            pid: treeNode.dataRef.id
          })
            .then(res => {
              if (res.code != 200) {
                this.$message.info('获取目录失败')
              }
              treeNode.dataRef.children = res.result.records
              this.treeData = [...this.treeData]
            })
            .catch(err => {
              console.log(err)
            })
          resolve()
        }, 100)
      })
    },

    // tree 获取选中元素监听事件
    onSelect(selectedKeys, info) {
      if (info.selected === true) {
        this.CategoryId = info.selectedNodes[0].data.props.id
        this.CategoryParentId = info.selectedNodes[0].data.props.pid
        getAction('/nlpcs/knowledgeBase/list', {
          categoryPathId: this.CategoryId
        })
          .then(res => {
            this.SourceData = res.result.records
          })
          .catch(err => {
            console.log(err)
          })
      } else {
        this.CategoryId = null
      }
    },

    // 打开类目面板
    CategoryOpenModel(type, item) {
      // 类目删除不需要获得核心词列表
      if (type === 'ScienceDEL') {
        this.visible = false
        deleteAction('/nlpcs/knowledgeBase/delete', {
          id: item.id
        })
          .then(res => {
            console.log(res)
          })
          .catch(err => {
            console.log(err)
          })
      } else {
        this.ModelType = type
        this.visible = true
        // 获取核心词列表
        getAction('/nlpcs/coreWords/list', {})
          .then(res => {
            this.CoreWordsData = res.result.records
          })
          .catch(err => {
            console.log(err)
          })
        // 判断除打开类目删除外的面板类型
        if (type === 'ScienceCRE') {
        } else if (type === 'ScienceEDI') {
          this.ScienceEDI.title = item.title
          this.ScienceEDI.id = item.id
        } else if (type === 'CoreWordEDI') {
          this.CoreWordName = item.content
          this.CoreWordID = item.id
        } else if (type === 'CoreWordDEL') {
          this.CoreWordID = item.id
        }
      }
    },

    // 类目面板确定事件
    modelDetermine() {
      this.visible = false
      this.ScienceCRE.categoryPathId = this.CategoryId
      this.ScienceEDI.categoryPathId = this.CategoryId
      if (this.ModelType === 'CategoryCRE') {
        postAction('/nlpcs/categoryPath/add', {
          pid: this.CategoryId,
          name: this.CategoryName
        })
          .then(res => {
            // this.getTreeCategory()
          })
          .catch(err => {
            console.log(err)
          })
      } else if (this.ModelType === 'CategoryEDI') {
        putAction('/nlpcs/categoryPath/edit', {
          id: this.CategoryId,
          pid: this.CategoryParentId,
          name: this.CategoryName
        })
          .then(res => {
            // this.getTreeCategory()
          })
          .catch(err => {
            console.log(err)
          })
      } else if (this.ModelType === 'CategoryDEL') {
        deleteAction('/nlpcs/categoryPath/delete', {
          id: this.CategoryId
        })
          .then(res => {
            // this.getTreeCategory()
          })
          .catch(err => {
            console.log(err)
          })
      } else if (this.ModelType === 'ScienceCRE') {
        if (this.CategoryId === null) {
          alert('选择类目')
        } else {
          postAction('/nlpcs/knowledgeBase/add', this.ScienceCRE)
            .then(res => {
              console.log(this.ScienceCRE)

              console.log(res)
            })
            .catch(err => {
              console.log(err)
            })
        }
      } else if (this.ModelType === 'ScienceEDI') {
        putAction('/nlpcs/knowledgeBase/edit', this.ScienceEDI)
          .then(res => {
            console.log(this.ScienceEDI)

            console.log(res)
          })
          .catch(err => {
            console.log(err)
          })
      } else if (this.ModelType === 'CoreWordCRE') {
        postAction('/nlpcs/coreWords/add', { content: this.CoreWordName })
          .then(res => {
            this.getCoreWords()
          })
          .catch(err => {
            console.log(err)
          })
      } else if (this.ModelType === 'CoreWordEDI') {
        var data = {
          id: this.CoreWordID,
          content: this.CoreWordName
        }
        putAction('/nlpcs/coreWords/edit', data)
          .then(res => {
            this.getCoreWords()
          })
          .catch(err => {
            console.log(err)
          })
      } else if (this.ModelType === 'CoreWordDEL') {
        deleteAction('/nlpcs/coreWords/delete', { id: this.CoreWordID })
          .then(res => {
            console.log(res)

            this.getCoreWords()
          })
          .catch(err => {
            console.log(err)
          })
      }
    },

    // 类目面板取消事件
    modelCancel() {
      this.visible = false
      this.CategoryName = ''
    },

    // 核心词select监听事件
    handleChange(e) {
      this.ScienceCRE.coreWordsId = this.CoreWordsData[e].id
      this.ScienceEDI.coreWordsId = this.CoreWordsData[e].id
    },

    handleImportExcel(info) {
      // if (info.file.status !== 'uploading') {
      //   console.log(info.file, info.fileList)
      // }
      // if (info.file.status === 'done') {
      //   this.$message.success(`${info.file.name} file uploaded successfully`)
      // } else if (info.file.status === 'error') {
      //   this.$message.error(`${info.file.name} file upload failed.`)
      // }
            if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 201) {
            let { message, result: { msg, fileUrl, fileName } } = info.file.response
            let href = window._CONFIG['domianURL'] + fileUrl
            this.$warning({
              title: message,
              content: (
                <div>
                  <span>{msg}</span><br/>3...
                  <span>具体详情请 <a href={href} target="_blank" download={fileName}>点击下载</a> </span>
                </div>
              )
            })
          } else {
            this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
          }
          this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`);
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `);
      }
    }
  }
}
</script>

<style>
.problemtrain {
  margin: 40px;
  min-height: calc(100vh - 80px);
}

/* 类目  知识列表才有flex布局左右分开 */
.main-content {
  display: flex;
  justify-content: space-between;
}
.main-inner-left {
  width: 30%;
}
.main-inner-right {
  width: 60%;
}
</style>